package org.ithang.tools.timer;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.ithang.application.account.bean.Account;
import org.ithang.application.account.service.AccountService;
import org.ithang.application.customer.service.CustomerService;
import org.ithang.application.grade.bean.Grade;
import org.ithang.application.grade.service.GradeService;
import org.ithang.application.invest.bean.InvestSum;
import org.ithang.application.invest.service.InvestService;
import org.ithang.application.invest.service.InvestSumService;
import org.ithang.application.teamBonus.bean.TeamBonus;
import org.ithang.application.teamBonus.service.TeamBonusService;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.tools.lang.DateUtils;
import org.ithang.tools.lang.GradeUtil;
import org.ithang.tools.model.Arith;
import org.ithang.tools.redis.Keys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;


/**
 * 任务Handler示例（Bean模式）
 *
 * 开发步骤：
 * 1、继承"IJobHandler"：“com.xxl.job.core.handler.IJobHandler”；
 * 2、注册到Spring容器：添加“@Component”注解，被Spring容器扫描为Bean实例；
 * 3、注册到执行器工厂：添加“@JobHandler(value="自定义jobhandler名称")”注解，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 * 4、执行日志：需要通过 "XxlJobLogger.log" 打印执行日志；
 *
 * 加速分润
 */
@JobHandler(value="teamBonusJobHandler")
@Component
public class TeamBonusJobHandler extends IJobHandler {

	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private GradeService gradeService;
	
	@Autowired
	private InvestSumService investSumService;
	
	@Autowired
	private InvestService investService;
	
	@Autowired
	private TeamBonusService teamBonusService;
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
    private KeyvalueService keyvalueService;
	
	private static Set<String> ids=new HashSet<>();
	
	private Logger logger=Logger.getLogger(TeamBonusJobHandler.class);
	
	@Override
	public ReturnT<String> execute(String param) throws Exception {
		logger.info("开始执行加速分润");
		
		String value=keyvalueService.get(Keys.IsTeamBonus).getValue();
		if(null==value||"0".equals(value.trim())){
			logger.info("加速分润开关未打开，结束执加速态分润");
			return SUCCESS; 
		}
		
		Map<String,Object> condition=new HashMap<>(5);
		condition.put("type", 0);
		List<Grade> grades=gradeService.query(condition);
		
		if(null==grades||grades.isEmpty()){
			return SUCCESS;
		}
					
		
		/*List<Account> accounts= accountService.list();
		
		if(null!=accounts&&!accounts.isEmpty()){
			for(Account account:accounts){
				if(null!=account.getTeam_invest_amount()&&account.getTeam_invest_amount()>0){
					
					Double rate=GradeUtil.getRate(grades,account.getTeam_invest_amount()==null?0:account.getTeam_invest_amount())/100D;
					
					if(null==account.getInvest_amount()){
						account.setInvest_amount(0D);
					}
					if(null==account.getTeam_bonus()){
						account.setTeam_bonus(0D);	
					}
					
					if(((account.getStatic_bonus()+account.getTeam_bonus())<account.getInvest_amount())&&rate>0){//如果 团队收益的小于个人投资本金的2倍 则继续分红
						
						Double bouns=Arith.mul(account.getInvest_amount(),rate);
						
						if((bouns+account.getStatic_bonus()+account.getTeam_bonus())>account.getInvest_amount()){
							bouns=account.getInvest_amount()-(account.getStatic_bonus()+account.getTeam_bonus());
						}
						
						TeamBonus teamBonus=new TeamBonus();
						teamBonus.setAmount(bouns);
						teamBonus.setCustomer_id(account.getCustomer_id());
						teamBonus.setType(0);
						teamBonus.setCreate_time(DateUtils.getSystime());
						
						teamBonusService.add(teamBonus);
						
						account.setAmount(Arith.add(account.getAmount(),bouns));
						account.setTeam_bonus(Arith.add(account.getTeam_bonus(),bouns));
						accountService.update(account);
					}
				}
			}
		}*/
		
		
		int maxGrade=customerService.getsInt("select ifnull(MAX(`grade`),0) mgrade from `customer`");
		if(0==maxGrade){//没有一个人有下级，直接根据个人投资总额计算加速利息
			
			List<Account> accounts=accountService.list();
			
			if(null!=accounts&&!accounts.isEmpty()){
				for(Account account:accounts){
					if((account.getTeam_bonus()+account.getStatic_bonus())<account.getInvest_amount()){
						double bonus=Arith.mul(account.getInvest_amount(),(GradeUtil.getRate(grades, Arith.div(account.getTeam_invest_amount(),100D,5))));//利息
						
						if(bonus>0){
							
							if((account.getTeam_bonus()+account.getStatic_bonus()+bonus)>account.getInvest_amount()){
								bonus=account.getInvest_amount()-(account.getTeam_bonus()+account.getStatic_bonus());
							}
							
							TeamBonus teamBonus=new TeamBonus();
							teamBonus.setAmount(bonus);
							teamBonus.setType(0);
							teamBonus.setCustomer_id(account.getCustomer_id());
							teamBonus.setCreate_time(DateUtils.getSystime());
							teamBonusService.add(teamBonus);//添加分润记录
							
							account.setAmount(account.getAmount()+bonus);
							account.setTeam_bonus(account.getTeam_bonus()+bonus);
							accountService.update(account);
						}
					}
				
				}
			}else{
				logger.info("没有人投资，结束执加速态分润");
				return SUCCESS;
			}
		}else{//在有下级的情况下计算利息
			List<Account> accounts= accountService.list();
			
			if(null!=accounts&&!accounts.isEmpty()){
				
				//{1}算出所有用户的团队投资的总收益
				for(Account account:accounts){
					if(account.getTeam_invest_amount()>0){
							Double rate=GradeUtil.getRate(grades,account.getTeam_invest_amount())/100D;
							Double bonus=Arith.mul(account.getTeam_invest_amount(),rate);
							
							account.setTotal_bonus(bonus);
							account.setTeam_total_bonus(0D);
					}else{
						account.setTotal_bonus(0D);
						account.setTeam_total_bonus(0D);
					}
				}
				
				//{2}算该用户下的所有用户的团队收益的总和
				for(Account account:accounts){
					for(Account act:accounts){
						if(account.getId()==act.getFrom_user()){
							account.setTeam_total_bonus(Arith.add(account.getTeam_total_bonus(),act.getTotal_bonus()));
						}
					}
				}
				
				//{3}该用户团队总收益-该用户下的所有用户的团队收益的总和
				for(Account account:accounts){
					double bonus=Arith.sub(account.getTotal_bonus(),account.getTeam_total_bonus());
					
					if((bonus+account.getStatic_bonus()+account.getTeam_bonus())>account.getInvest_amount()){
						bonus=Arith.sub(account.getInvest_amount(),(Arith.add(account.getStatic_bonus(),account.getTeam_bonus())));
					}
					
					account.setTeam_bonus(Arith.add(account.getTeam_bonus(),bonus));
					accountService.update(account);
					
					TeamBonus teamBonus=new TeamBonus();
					teamBonus.setAmount(bonus);
					teamBonus.setCustomer_id(account.getCustomer_id());
					teamBonus.setType(0);
					teamBonus.setCreate_time(DateUtils.getSystime());
					teamBonusService.add(teamBonus);
					
				}
				
			}
		}
		
		logger.info("结束执加速态分润");
		return SUCCESS;
	}
	
	
}
